package com.vitabuybuy.tv.ui.cart

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.RegexUtils
import com.library.common.base.BaseActivity
import com.library.common.base.MessageModel
import com.library.common.dto.MessageEvent
import com.library.common.ext.mmkv
import com.library.common.ext.setOnclickNoRepeat
import com.vitabuybuy.tv.BR
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ActivityConfirmOrderBinding
import com.vitabuybuy.tv.dto.AddressListDto
import com.library.common.toast.XToast
import com.library.common.util.DensityUtil
import com.library.common.widget.RecycleViewDivider
import com.vitabuybuy.tv.ui.cart.adapter.StoreAdapter
import com.vitabuybuy.tv.ui.cart.viewmodel.ConfirmOrderViewModel
import com.vitabuybuy.tv.ui.mine.address.AddressActivity
import com.vitabuybuy.tv.utils.EventCode
import com.library.common.util.MMKVContancts

import com.vitabuybuy.tv.dialog.StoreCouponsPopup
import kotlinx.android.synthetic.main.activity_confirm_order.*
import org.greenrobot.eventbus.EventBus

class ConfirmOrderActivity : BaseActivity<ConfirmOrderViewModel, ActivityConfirmOrderBinding>() {
    override val isUseBaseTitleBar: Boolean
        get() = true
    override val layoutId: Int
        get() = R.layout.activity_confirm_order

    private var idList: ArrayList<Int>? = null
    private var goodId: Int? = 0
    private var quantity: Int? = 0
    private var groupBuyId: Int? = 0
    private var liveId: Int? = 0
    private var from: Int? = SETTLEMENT_ORDER
    private var chooseCouponId = ""
    private var couponsPopup: StoreCouponsPopup? = null
    private lateinit var storeAdapter: StoreAdapter
    private var remarkMap = HashMap<Int, String>()

    override fun onGetBundle(bundle: Bundle?) {
        from = bundle?.getInt("from")
        when (from) {
            BUY_NOW, GROUP_BUY_CREATE, GROUP_BUY_JOIN, GROUP_BUY_BY_LIMIT_JOIN -> {
                goodId = bundle?.getInt("goodId")
                quantity = bundle?.getInt("quantity")
                liveId = bundle?.getInt("liveId")
                if (from == GROUP_BUY_CREATE || from == GROUP_BUY_JOIN || from == GROUP_BUY_BY_LIMIT_JOIN)
                    groupBuyId = bundle?.getInt("groupBuyId")
            }
            else -> {
                idList = bundle?.getIntegerArrayList("idList")
            }
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        setTitle(getString(R.string.confirm_order))
        mBinding.mViewModel = viewModel
        layoutPlatfromCoupons.visibility = when (from) {
            GROUP_BUY_CREATE, GROUP_BUY_JOIN, GROUP_BUY_BY_LIMIT_JOIN -> View.GONE
            else -> if (liveId == 0) View.VISIBLE else View.GONE
        }
        from?.run {
            storeAdapter = StoreAdapter(this, liveId)
            rcvOrder.apply {
                layoutManager = LinearLayoutManager(mContext)
                addItemDecoration(RecycleViewDivider(mContext, DensityUtil.dip2px(6f)))
                adapter = storeAdapter
            }
        }
        etEmailAddress.setText(mmkv.decodeString(MMKVContancts.USER_EMAIL, ""))
    }

    override fun observeData() {
        viewModel.apply {
            when (from) {
                BUY_NOW -> {
                    buyNow(goodId, liveId, quantity)
                }
                GROUP_BUY_CREATE, GROUP_BUY_JOIN, GROUP_BUY_BY_LIMIT_JOIN -> {
                    buyByGroup(goodId, quantity)
                }
                else -> {
                    calculateCart(idList, from)
                }
            }
            getAddressList()
            settlementDto.observe(this@ConfirmOrderActivity, Observer {
                storeAdapter.setNewData(it.storeList)
            })
            addressList.observe(this@ConfirmOrderActivity, Observer {
                when (it.size) {
                    0 -> {
                        tvNotAddress.visibility = View.VISIBLE
                        rlreceiverAddress.visibility = View.GONE
                    }
                    else -> {
                        tvNotAddress.visibility = View.GONE
                        rlreceiverAddress.visibility = View.VISIBLE
                        var isSetup = false
                        for (address in it) {
                            if (address.isDefaulted) {
                                isSetup = true
                                mBinding.setVariable(BR.addressDto, address)
                            }
                        }
                        if (!isSetup) {
                            mBinding.setVariable(BR.addressDto, it[0])
                        }
                    }
                }
            })
            canUserCoupnList.observe(this@ConfirmOrderActivity, Observer { it ->
                if (it.size == 0) {
                    XToast.normal(getString(R.string.this_store_has_no_coupons))
                    return@Observer
                }
                couponsPopup = StoreCouponsPopup(
                    mContext, it, StoreCouponsPopup.USER_COUPONS
                ) { couponDto, _ ->
                    viewModel.chooseStoreCouponIds[chooseCouponId] = couponDto.id
                    viewModel.settlementDto.value?.run {
                        val params = HashMap<String, Any?>()
                        val idList = ArrayList<Map<String, Int?>>()
                        for (storeBean in this.storeList) {
                            for (itemBean in storeBean.itemList) {
                                idList.add(mapOf(Pair("id", itemBean.id)))
                            }
                        }
                        val couponIdList = ArrayList<Int>()
                        for (idMap in viewModel.chooseStoreCouponIds) {
                            if (idMap.value != -1) {
                                couponIdList.add(idMap.value)
                            }
                        }
                        params["itemList"] = idList
                        params["couponIdList"] = couponIdList
                        viewModel.calculateAmount(params)
                        couponsPopup?.dismiss()
                    }
                }
                couponsPopup?.showPopupWindow()
            })
        }
    }

    override fun eventHandling() {
        setOnclickNoRepeat(
            tvNotAddress,
            rlreceiverAddress,
            btnSubmitOrder,
            layoutPlatfromCoupons
        ) { v ->
            when (v) {
                rlreceiverAddress, tvNotAddress -> {
                    AddressActivity.openActivity(mContext, 10002)
                }
                layoutPlatfromCoupons -> {
                    viewModel.settlementDto.value?.run {
                        chooseCouponId = "platform"
                        val params = HashMap<String, Any?>()
                        val idList = ArrayList<Map<String, Int?>>()
                        for (storeBean in this.storeList) {
                            for (itemBean in storeBean.itemList) {
                                idList.add(mapOf(Pair("id", itemBean.id)))
                            }
                        }
                        params["itemList"] = idList
                        viewModel.foundCanUserCoupons(params)
                    }
                }
                btnSubmitOrder -> {
                    when {
                        mBinding.addressDto == null -> XToast.normal(getString(R.string.pls_setup_address))
                        etEmailAddress.text.isEmpty() -> XToast.normal(getString(R.string.enter_email))
                        !RegexUtils.isEmail(etEmailAddress.text) -> XToast.normal(getString(R.string.please_enter_correct_email))
                        else -> {
                            when (from) {
                                BUY_NOW, BUY_AGAIN, SETTLEMENT_ORDER -> {
                                    viewModel.settlementDto.value?.run {
                                        val idlist = ArrayList<Int>()
                                        for (store in this.storeList) {
                                            for (item in store.itemList) {
                                                idlist.add(item.id)
                                            }
                                        }
                                        val couponIdList = ArrayList<Int>()
                                        for (idMap in viewModel.chooseStoreCouponIds) {
                                            couponIdList.add(idMap.value)
                                        }
                                        couponIdList.addAll(couponIdList)
                                        viewModel.submitOrder(
                                            idlist,
                                            couponIdList,
                                            mBinding.addressDto?.id,
                                            etEmailAddress.text.toString(),
                                            remarkMap,
                                            liveId
                                        )
                                    }
                                }
                                GROUP_BUY_CREATE -> {
                                    viewModel.settlementDto.value?.run {
                                        viewModel.submitGroupBuyCreate(
                                            groupBuyId,
                                            this.storeList[0].itemList[0].id,
                                            mBinding.addressDto?.id,
                                            etEmailAddress.text.toString(),
                                            remarkMap
                                        )
                                    }
                                }
                                GROUP_BUY_JOIN -> {
                                    viewModel.settlementDto.value?.run {
                                        viewModel.submitGroupBuyJoin(
                                            groupBuyId,
                                            this.storeList[0].itemList[0].id,
                                            mBinding.addressDto?.id,
                                            etEmailAddress.text.toString(),
                                            remarkMap
                                        )
                                    }
                                }
                                GROUP_BUY_BY_LIMIT_JOIN -> {
                                    viewModel.settlementDto.value?.run {
                                        viewModel.submitGroupBuyBylimitJoin(
                                            groupBuyId,
                                            this.storeList[0].itemList[0].id,
                                            mBinding.addressDto?.id,
                                            etEmailAddress.text.toString(),
                                            remarkMap
                                        )
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        storeAdapter.chooseStoreCouponListener = { position ->
            viewModel.settlementDto.value?.run {
                chooseCouponId = storeList[position].id.toString()
                val params = HashMap<String, Any?>()
                params["storeId"] = storeList[position].id
                val idList = ArrayList<Map<String, Int?>>()
                for (itemBean in storeList[position].itemList) {
                    idList.add(mapOf(Pair("id", itemBean.id)))
                }
                params["itemList"] = idList
                viewModel.foundCanUserCoupons(params)
            }
        }
        storeAdapter.remarkListener = { stroeId: Int, remark: String ->
            if (remark.isEmpty()) {
                if (remarkMap.containsKey(stroeId)) {
                    remarkMap.remove(stroeId)
                }
            } else {
                remarkMap[stroeId] = remark
            }
        }
    }

    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            1 -> {
                viewModel.settlementDto.value?.run {
                    OrderPayActivity.openActivity(
                        mContext,
                        msg.obj as Int,
                        if (this.paymentAmount == 0.0) this.goodsAmount else this.paymentAmount,
                        OrderPayActivity.FROM_PAY_ORDER
                    )
                    EventBus.getDefault().post(MessageEvent(EventCode.updae_cart))
                    finish()
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        if (requestCode == 10002) {
            mBinding.setVariable(
                BR.addressDto,
                data?.extras?.getSerializable("addressDto") as AddressListDto
            )
            tvNotAddress.visibility = View.GONE
            rlreceiverAddress.visibility = View.VISIBLE
        }
    }

    companion object {
        const val BUY_AGAIN = 10001
        const val BUY_NOW = 10002
        const val SETTLEMENT_ORDER = 10003
        const val GROUP_BUY_CREATE = 10004
        const val GROUP_BUY_JOIN = 10005
        const val GROUP_BUY_BY_LIMIT_JOIN = 10006
        fun openActivity(mContext: BaseActivity<*, *>, idList: ArrayList<Int>, from: Int) {
            mContext.startActivity(
                bundleOf(Pair("idList", idList), Pair("from", from)),
                ConfirmOrderActivity::class.java
            )
        }

        fun openActivity(mContext: BaseActivity<*, *>, goodId: Int, quantity: Int, from: Int) {
            mContext.startActivity(
                bundleOf(
                    Pair("goodId", goodId),
                    Pair("quantity", quantity),
                    Pair("from", from)
                ),
                ConfirmOrderActivity::class.java
            )
        }

        fun openActivityByLive(
            mContext: BaseActivity<*, *>,
            goodId: Int,
            quantity: Int,
            liveId: Int?,
            from: Int
        ) {
            mContext.startActivity(
                bundleOf(
                    Pair("goodId", goodId),
                    Pair("quantity", quantity),
                    Pair("liveId", liveId),
                    Pair("from", from)
                ),
                ConfirmOrderActivity::class.java
            )
        }


        fun openActivity(
            mContext: BaseActivity<*, *>,
            goodId: Int,
            quantity: Int,
            groupBuyId: Int,
            from: Int
        ) {
            mContext.startActivity(
                bundleOf(
                    Pair("goodId", goodId),
                    Pair("quantity", quantity),
                    Pair("groupBuyId", groupBuyId),
                    Pair("from", from)
                ),
                ConfirmOrderActivity::class.java
            )
        }
    }
}
